<template>
  <div class="map" id="map" ref="mapRef">
    <div class="map__toolbar">
      <div class="map__toolbar-group">
        <CesiumButton icon="/images/screen.png" title="全屏" @click="handleFullScreen" />
        <CesiumDropdown v-model="measureType" :options-map="measureTypeMap" placeholder="测量工具"
          @change="handleMeasureSelect" />
        <CesiumButton v-if="measureType" type="warning" title="清除测量" @click="clearMeasure">
          清除
        </CesiumButton>
      </div>
    </div>
    <div id="container" ref="containerRef" class="cesium-container"></div>
    <div class="map__coordinates" ref="coordinatesRef">
      <span class="map__coordinates-text">
        经度：{{ coordinates.longitude }} 纬度：{{ coordinates.latitude }} 高度：{{ coordinates.altitude }}km
      </span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import cesiumUtils from '@/utils/cesiumUtils'
import pointsConfig from '@/config/points.json'
import tilesConfig from '@/config/tiles.json'

const emit = defineEmits(['map-loaded', 'full-screen'])

let cesiumTools = null
let viewer = null

const coordinates = ref({
  longitude: '',
  latitude: '',
  altitude: ''
})
const coordinatesRef = ref(null)
const measureType = ref('')
const containerRef = ref(null)

// 测量类型映射
const measureTypeMap = {
  'distance': '距离测量',
  'area': '面积测量',
  'height': '高差测量',
  'angle': '角度测量'
}

const showMeasureMenu = ref(false)

// 全屏切换
function handleFullScreen() {
  emit('full-screen')
}

// 添加3DTiles
function add3DTiles() {
  tilesConfig.tiles.forEach(tile => {
    const tileSet = cesiumTools.add3DTile(tile.url, tile.options)
    viewer.zoomTo(tileSet)
  })
}

// 添加点位
function addPoints() {
  pointsConfig.points.forEach(point => {
    if (point.latitude && point.longitude) {
      cesiumTools.addEntity(point, point.type)
    }
  })
}


// 处理测量类型选择
const handleMeasureSelect = (type) => {
  measureType.value = type
  showMeasureMenu.value = false
  cesiumTools.startMeasure(type)
}


// 清除测量
const clearMeasure = () => {
  cesiumTools.clearMeasure()
  measureType.value = ''
}

// 处理坐标显示
function handleMoveDegress(position) {
  if (position) {
    coordinates.value.longitude = position.long
    coordinates.value.latitude = position.lat
    coordinates.value.altitude = position.alti
    coordinatesRef.value.style = "display:block"
  } else {
    coordinatesRef.value.style = "display:none"
  }
}

// 处理渲染后事件
function handlePostRender(position, isBehind) {
  if (position && !isBehind) {
    // 处理位置更新
  }
}

// 处理点击事件
function handleClick(entity, position, flag) {
  if (flag && entity.info) {
    console.log('点击实体:', entity.info)
  }
}

onMounted(() => {
  try {
    const container = document.getElementById("container")
    if (!container) {
      throw new Error('Map container element not found')
    }
    
    cesiumTools = cesiumUtils(container)
    viewer = cesiumTools.init({
      openDebug: true,
      startGlobeRotate: false,
      defaultImagery: 0
    })

    // 添加事件监听
    try {
      // cesiumTools.addClickEvent(handleClick)
      cesiumTools.addDoubleClickEvent()
      cesiumTools.addPostRenderEvent(handlePostRender)
      cesiumTools.moveDegress(handleMoveDegress)
    } catch (error) {
      console.error('Error adding event listeners:', error)
    }

    try {
      add3DTiles()
      // addPoints()
    } catch (error) {
      console.error('Error adding map layers:', error)
    }

    // 发出地图加载完成事件
    try {
      emit('map-loaded', cesiumTools, viewer)
    } catch (error) {
      console.error('Error emitting map-loaded event:', error)
    }
  } catch (error) {
    console.error('Error initializing Cesium:', error)
    // 发出错误事件以便父组件处理
    emit('map-error', error)
  }
})

onBeforeUnmount(() => {
  if (cesiumTools) {
    cesiumTools.destroy()
  }
})
</script>

<style scoped lang="scss">
.map {
  width: 100%;
  height: 100%;
  position: relative;

  &__toolbar {
    position: absolute;
    left: 5px;
    top: 5px;
    z-index: 1;
    padding: 5px;

    &-group {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }

  &__coordinates {
    position: absolute;
    right: 20px;
    bottom: 20px;
    z-index: 1;
    max-width: 500px;
    height: 30px;
    display: none;
    background: rgba(0, 0, 0, 0.5);
    padding: 0 10px;
    border-radius: 4px;

    &-text {
      color: white;
      font-size: 14px;
      line-height: 30px;
    }
  }
}

.cesium-container {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
}
</style>